﻿using System;
using System.Collections.Generic;
using System.Text;
using TTServer.Messages;
using TTServer.Objects;
using libReadWrite;
using libCommonClass;

namespace TTServer
{
    public class MessageReader
    {
        private BigEndianReader reader = null;

        public MessageReader(BigEndianReader in_reader)
        {
            this.reader = in_reader;
        }


        public TTMessage GetMessage()
        {
            TTMessage message = null;

            MessageFactory messageManager = MessageFactory.GetInstance();

            try
            {

                /////////////////////////////////////////////
                //TO DO: Read the message sent by the client

                byte msgID = reader.ReadByte();

                int msgLength = reader.ReadInt32();

                TTMessage msg = messageManager.CreateMessage(msgID);

                if (msg != null)
                {
                    msg.ReadMessage(reader);             
                }
                else {
                    if (msgLength > 0)
                    {
                        reader.Skip(msgLength);
                    }
                    else if (msgLength == Global.NO_LENGTH_CODE)
                    {
                        throw new Exception("A strange message without lenght information");
                    }
                    else {
                        throw new Exception("A strange message without lenght information");
                    }
                }

                message = msg;

            }
            catch(Exception ex)
            {
                throw new Exception("MessageReader.GetMessage(): Failure" + ex.Message);
            }

            return message;
        }
    }
}
